#! /usr/bin/python
# -*- coding: utf-8 -*-
from author_model import Author
from gsw_model import GushiWen
from authorziliao_model import AuthorZiliao
from gsw_mingju_model import Mingju
import urllib2
import urllib
import json
import os

sumPage = 1000


# https://img.gushiwen.org/authorImg/caozhi.jpg


def get_response(parametrise, url):
    response_body = urllib.urlencode(parametrise)
    request = urllib2.Request(url, response_body)
    response = urllib2.urlopen(request)
    response_data = response.read()
    jsonStr = json.loads(response_data)
    return jsonStr


def get_author(p, chaodai=''):
    """
    获取古诗文的作者
    :param p: 页数
    :param chaodai:朝代
    :return: 作者数据（数组）
    """
    global sumPage
    if p > sumPage != 0:
        return None
    url = 'https://app.gushiwen.org/api/author/Default.aspx'
    parametrise = {
        'id': 0,
        'p': p,
        'c': chaodai,
        'pwd': '',
        'token': 'gswapi'
    }
    jsonStr = get_response(parametrise, url)
    sumPage = jsonStr.get('sumPage')
    authors = jsonStr.get('authors')
    author_list = []
    for value in authors:
        author_data = Author(value)
        author_list.append(author_data)
    return author_list


def get_sw_by_author(id, p):
    """
    根据作者id，获取改作者的所有古诗文
    :param id: 作者id
    :param p: 页数
    :return: 古诗文数据（字典）
    """
    global sumPage
    if p > sumPage != 0:
        return None
    url = 'https://app.gushiwen.org/api/author/authorsw2.aspx'
    parametrise = {
        'id': id,
        'page': p,
        'token': 'gswapi'
    }
    jsonStr = get_response(parametrise, url)
    sumPage = jsonStr.get('sumPage')
    tb_gushiwens = jsonStr.get('tb_gushiwens')
    gushiwens_list = []
    for value in tb_gushiwens:
        gushiwen_data = GushiWen(value)
        gushiwens_list.append(gushiwen_data)
    return gushiwens_list


def get_ziliao_by_author(id):
    """
    根据作者id，获取该作者的所有资料
    :param id: 作者id
    :return: 资料数据（字典）
    """

    url = 'https://app.gushiwen.org/api/author/author2.aspx'
    parametrise = {
        'id': id,
        'token': 'gswapi'
    }
    jsonStr = get_response(parametrise, url)
    tb_ziliaos = jsonStr.get('tb_ziliaos')
    ziliaos = tb_ziliaos.get('ziliaos')
    ziliaos_list = []
    for value in ziliaos:
        ziliao_data = AuthorZiliao(value)
        ziliaos_list.append(ziliao_data)
    return ziliaos_list


def getmingju(p, c='', t=''):
    """
    根据作者id，获取改作者的所有古诗文
    :param id: 作者id
    :param p: 页数
    :return: 古诗文数据（字典）
    """
    global sumPage
    if p > sumPage != 0:
        return None
    url = 'https://app.gushiwen.org/api/mingju/Default2.aspx'
    parametrise = {
        'p': p,
        'c': c,
        't': t,
        'id': 0,
        'pwd': '',
        'token': 'gswapi'
    }
    jsonStr = get_response(parametrise, url)
    sumPage = jsonStr.get('sumPage')
    tb_gushiwens = jsonStr.get('mingjus')
    gushiwens_list = []
    for value in tb_gushiwens:
        gushiwen_data = Mingju(value)
        gushiwens_list.append(gushiwen_data)
    return gushiwens_list


def getgushiwen(id):
    """
    根据古诗文id获取翻译和赏析
    :param id:
    :return:
    """
    parametrise = {
        'id': id,
        'token': 'gswapi'
    }
    url = 'https://app.gushiwen.org/api/shiwen/shiwenv.aspx'
    jsonStr = get_response(parametrise, url)
    return jsonStr


def save_img(file_name, file_path='author/img'):
    """
    下载古诗文图片
    :param file_name:
    :param file_path:
    :return:
    """
    # 保存图片到磁盘文件夹 file_path中，默认为当前脚本运行目录下的 book\img文件夹
    try:
        if not os.path.exists(file_path):
            print('文件夹', file_path, '不存在，重新建立')
            # os.mkdir(file_path)
            os.makedirs(file_path)
    except IOError as e:
        print('文件操作失败', e)
    # 获得图片后缀
    file_suffix = '.jpg'
    img_url = 'https://img.gushiwen.org/authorImg/' + file_name + file_suffix
    # 拼接图片名（包含路径）
    filename = '{}{}{}{}'.format(file_path, os.sep, file_name, file_suffix)
    # 下载图片，并保存到文件夹中
    urllib.urlretrieve(img_url, filename=filename)


def getyizhushang(id,type):
    """

    :param id:
    :param type:
    :return:
    """
    parametrise = {
        'id': id,
        'value': type,
        'token': 'gswapi'
    }
    url = 'https://app.gushiwen.org/api/shiwen/ajaxshiwencont.aspx'
    jsonStr = get_response(parametrise, url)
    return jsonStr